<script>
import {createModelForVue, createProps} from '@/utils';
import {createFormDefinition} from '@/components/hhd/design/FormDesigner/types';
import FormEngineUtils from '@/components/hhd/design/FormEngine/FormEngineUtils';
import FormEngineRender from '@/components/hhd/design/FormEngine/FormEngineRender';
import './style.css';
import {VueProperties} from '@/utils/FormDesignUtils';

export default {
  name: 'FormEngine',
  model: createModelForVue('formModel'),
  props: {
    formDefinition: createProps(Object, createFormDefinition),
    view: createProps(String),
    formModel: createProps(Object, () => undefined),
    action: createProps(String)
  },
  data() {
    return {
      context: undefined
    };
  },
  mounted() {
    VueProperties.h = this.$createElement;
  },
  render() {
    return this.checkPropsValues() ? this.renderForm() : undefined;
  },
  methods: {
    renderForm() {
      if (this.formModel) {//如果model不是空的, 那么不需要初始化了
        let context = this.context = FormEngineUtils.createContext(this);
        return context.check() ? FormEngineRender.render(context) : undefined;
      } else {
        this.context = FormEngineUtils.createContext(this, false);
        this.initFormData(() => {
          this.$emit('inited')
        });
      }
    },
    checkFormData() {
      return this.context.checkFormData();
    },
    autoRelation() {
      return this.context.autoRelation();
    },
    checkPropsValues() {
      return !!this.formDefinition && !!this.view && !!this.action;
    },
    initFormData(callback) {
      this.context && this.context.initFormData(callback);
    },
    resetAction() {
      this.context && this.context.resetAction()
    },
  }
};
</script>